home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / greps.zip / GREP.C < prev    next >
C/C++ Source or Header  |  1993-09-17  |  27KB  |  1,008 lines

  1. /* grep - print lines matching an extended regular expression
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written June, 1988 by Mike Haertel
  19.    BMG speedups added July, 1988 by James A. Woods and Arthur David Olson  */
  20.  
  21. #include <stdio.h>
  22.  
  23. #if defined(USG) || defined(STDC_HEADERS)
  24. #include <string.h>
  25. #ifndef bcopy
  26. #define bcopy(s,d,n)    memcpy((d),(s),(n))
  27. #endif
  28. #ifndef index
  29. #define index strchr
  30. #endif
  31. #else
  32. #include <string.h>
  33. #endif
  34.  
  35. #ifdef HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38.  
  39. #ifndef STDC_HEADERS
  40. extern char *getenv();
  41. #endif
  42. extern int errno;
  43.  
  44. extern char *sys_errlist[];
  45.  
  46. #include "dfa.h"
  47. #include "regex.h"
  48. #include "getopt.h"
  49.  
  50. /* Used by -w */
  51. #define WCHAR(C) (ISALNUM(C) || (C) == '_')
  52.  
  53. #define MAX(a, b) ((a) > (b) ? (a) : (b))
  54.  
  55. /* Exit status codes. */
  56. #define MATCHES_FOUND 0        /* Exit 0 if no errors and matches found. */
  57. #define NO_MATCHES_FOUND 1    /* Exit 1 if no matches were found. */
  58. #define ERROR 2            /* Exit 2 if some error occurred. */
  59.  
  60. /* Error is set true if something awful happened. */
  61. static int error;
  62.  
  63. /* The program name for error messages. */
  64. static char *prog;
  65.  
  66. /* We do all our own buffering by hand for efficiency. */
  67. static char *buffer;        /* The buffer itself, grown as needed. */
  68. static bufbytes;        /* Number of bytes in the buffer. */
  69. static size_t bufalloc;        /* Number of bytes allocated to the buffer. */
  70. static bufprev;            /* Number of bytes that have been forgotten.
  71.                    This is used to get byte offsets from the
  72.                    beginning of the file. */
  73. static bufread;            /* Number of bytes to get with each read(). */
  74.  
  75. static void
  76. initialize_buffer()
  77. {
  78.   bufread = 8192;
  79.   bufalloc = bufread + bufread / 2;
  80.   buffer = malloc(bufalloc);
  81.   if (! buffer)
  82.     {
  83.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  84.           sys_errlist[errno]);
  85.       exit(ERROR);
  86.     }
  87. }
  88.  
  89. /* The current input file. */
  90. static fd;
  91. static char *filename;
  92. static eof;
  93.  
  94. /* Fill the buffer retaining the last n bytes at the beginning of the
  95.    newly filled buffer (for backward context).  Returns the number of new
  96.    bytes read from disk. */
  97. static int
  98. fill_buffer_retaining(n)
  99.      int n;
  100. {
  101.   char *p, *q;
  102.   int i;
  103.  
  104.   /* See if we need to grow the buffer. */
  105.   if (bufalloc - n <= bufread)
  106.     {
  107.       while (bufalloc - n <= bufread)
  108.     {
  109.       bufalloc *= 2;
  110.       bufread *= 2;
  111.     }
  112.       buffer = realloc(buffer, bufalloc);
  113.       if (! buffer)
  114.     {
  115.       fprintf(stderr, "%s: Memory exhausted (%s)\n", prog,
  116.           sys_errlist[errno]);
  117.       exit(ERROR);
  118.     }
  119.     }
  120.  
  121.   bufprev += bufbytes - n;
  122.  
  123.   /* Shift stuff down. */
  124.   for (i = n, p = buffer, q = p + bufbytes - n; i--; )
  125.     *p++ = *q++;
  126.   bufbytes = n;
  127.  
  128.   if (eof)
  129.     return 0;
  130.  
  131.   /* Read in new stuff. */
  132.   i = read(fd, buffer + bufbytes, bufread);
  133.   if (i < 0)
  134.     {
  135.       fprintf(stderr, "%s: read on %s failed (%s)\n", prog,
  136.           filename ? filename : "<stdin>", sys_errlist[errno]);
  137.       error = 1;
  138.     }
  139.  
  140.   /* Kludge to pretend every nonempty file ends with a newline. */
  141.   if (i == 0 && bufbytes > 0 && buffer[bufbytes - 1] != '\n')
  142.     {
  143.       eof = i = 1;
  144.       buffer[bufbytes] = '\n';
  145.     }
  146.  
  147.   bufbytes += i;
  148.   return i;
  149. }
  150.  
  151. /* Various flags set according to the argument switches. */
  152. static trailing_context;    /* Lines of context to show after matches. */
  153. static leading_context;        /* Lines of context to show before matches. */
  154. static byte_count;        /* Precede output lines the byte count of the
  155.                    first character on the line. */
  156. static no_filenames;        /* Do not display filenames. */
  157. static line_numbers;        /* Precede output lines with line numbers. */
  158. static silent;            /* Produce no output at all.  This switch
  159.                    is bogus, ever hear of /dev/null? */
  160. static int whole_word;        /* Match only whole words.  Note that if
  161.                    backreferences are used this depends on
  162.                    the regex routines getting leftmost-longest
  163.                    right, which they don't right now if |
  164.                    is also used. */
  165. static int whole_line;        /* Match only whole lines.  Backreference
  166.                    caveat applies here too.  */
  167. static nonmatching_lines;    /* Print lines that don't match the regexp. */
  168.  
  169. static bmgexec;            /* Invoke Boyer-Moore-Gosper routines */
  170.  
  171. /* The compiled regular expression lives here. */
  172. static struct regexp reg;
  173.  
  174. /* The compiled regular expression for the backtracking matcher lives here. */
  175. static struct re_pattern_buffer regex;
  176.  
  177. /* Pointer in the buffer after the last character printed. */
  178. static char *printed_limit;
  179.  
  180. /* True when printed_limit has been artifically advanced without printing
  181.    anything. */
  182. static int printed_limit_fake;
  183.  
  184. /* Print a line at the given line number, returning the number of
  185.    characters actually printed.  Matching is true if the line is to
  186.    be considered a "matching line".  This is only meaningful if
  187.    surrounding context is turned on. */
  188. static int
  189. print_line(p, number, matching)
  190.      char *p;
  191.      int number;
  192.      int matching;
  193. {
  194.   int count = 0;
  195.  
  196.   if (silent)
  197.     {
  198.       do
  199.     ++count;
  200.       while (*p++ != '\n');
  201.       printed_limit_fake = 0;
  202.       printed_limit = p;
  203.       return count;
  204.     }
  205.  
  206.   if (filename && !no_filenames)
  207.     printf("%s%c", filename, matching ? ':' : '-');
  208.   if (byte_count)
  209.     printf("%d%c", p - buffer + bufprev, matching ? ':' : '-');
  210.   if (line_numbers)
  211.     printf("%d%c", number, matching ? ':' : '-');
  212.   do
  213.     {
  214.       ++count;
  215.       putchar(*p);
  216.     }
  217.   while (*p++ != '\n');
  218.   printed_limit_fake = 0;
  219.   printed_limit = p;
  220.   return count;
  221. }
  222.  
  223. /* Print matching or nonmatching lines from the current file.  Returns a
  224.    count of matching or nonmatching lines. */
  225. static int
  226. grep()
  227. {
  228.   int retain = 0;        /* Number of bytes to retain on next call
  229.                    to fill_buffer_retaining(). */
  230.   char *search_limit;        /* Pointer to the character after the last
  231.                    newline in the buffer. */
  232.   char saved_char;        /* Character after the last newline. */
  233.   char *resume;            /* Pointer to where to resume search. */
  234.   int resume_index = 0;        /* Count of characters to ignore after
  235.                    refilling the buffer. */
  236.   int line_count = 1;        /* Line number. */
  237.   int try_backref;        /* Set to true if we need to verify the
  238.                    match with a backtracking matcher. */
  239.   int initial_line_count;    /* Line count at beginning of last search. */
  240.   char *match;            /* Pointer to the first character after the
  241.                    string matching the regexp. */
  242.   int match_count = 0;        /* Count of matching lines. */
  243.   char *matching_line;        /* Pointer to first character of the matching
  244.                    line, or of the first line of context to
  245.                    print if context is turned on. */
  246.   char *real_matching_line;    /* Pointer to the first character of the
  247.                    real matching line. */
  248.   char *next_line;        /* Pointer to first character of the line
  249.                    following the matching line. */
  250.   char *last_match_limit;    /* Pointer after last matched line. */
  251.   int pending_lines = 0;    /* Lines of context left over from last match
  252.                    that we have to print. */
  253.   static first_match = 1;    /* True when nothing has been printed. */
  254.   int i;
  255.   char *tmp;
  256.   char *execute();
  257.  
  258.   printed_limit_fake = 0;
  259.   
  260.   while (fill_buffer_retaining(retain) > 0)
  261.     {
  262.       /* Find the last newline in the buffer. */
  263.       search_limit = buffer + bufbytes;
  264.       while (search_limit > buffer && search_limit[-1] != '\n')
  265.     --search_limit;
  266.       if (search_limit == buffer)
  267.     {
  268.       retain = bufbytes;
  269.       continue;
  270.     }
  271.  
  272.       /* Save the character after the last newline so regexecute can write
  273.      its own sentinel newline. */
  274.       saved_char = *search_limit;
  275.  
  276.       /* Search the buffer for a match. */
  277.       printed_limit = buffer;
  278.       resume = buffer + resume_index;
  279.       last_match_limit = resume;
  280.       initial_line_count = line_count;
  281.  
  282.  
  283.       /* In retrospect, I have to say that the following code sucks.
  284.      For an example of how to do this right, see the fgrep
  285.      driver program that I wrote around a year later.  I'm
  286.      too lazy to retrofit that to egrep right now (the
  287.      pattern matchers have different needs).  */
  288.  
  289.  
  290.       while (match = execute(®, resume, search_limit, 0, &line_count, &try_backref))
  291.     {
  292.       /* Find the beginning of the matching line. */
  293.       matching_line = match;
  294.       while (matching_line > resume && matching_line[-1] != '\n')
  295.         --matching_line;
  296.       real_matching_line = matching_line;
  297.  
  298.       /* Find the beginning of the next line. */
  299.       next_line = match;
  300.       while (next_line < search_limit && *next_line++ != '\n')
  301.         ;
  302.  
  303.       /* If a potential backreference is indicated, try it out with
  304.          a backtracking matcher to make sure the line is a match.
  305.          This is hairy because we need to handle whole_line and
  306.          whole_word matches specially.  The method was stolen from
  307.          GNU fgrep.  */
  308.       if (try_backref)
  309.         {
  310.           struct re_registers regs;
  311.           int beg, len, maxlen, ret;
  312.  
  313.           beg = 0;
  314.           for (maxlen = next_line - matching_line - 1; beg <= maxlen; ++beg)
  315.         {
  316.           /* See if the matching line matches when backreferences
  317.              are considered... */
  318.           ret = re_search (®ex, matching_line, maxlen,
  319.                    beg, maxlen - beg, ®s);
  320.           if (ret == -1)
  321.             goto fail;
  322.           beg = ret;
  323.           len = regs.end[0] - beg;
  324.           /* Ok, now check if it subsumed the whole line if -x */
  325.           if (whole_line && (beg != 0 || len != maxlen))
  326.             goto fail;
  327.           /* If -w then check if the match aligns with word
  328.              boundaries.  We have to do this iteratively, because
  329.              (a) The line may contain more than one occurence
  330.              of the pattern, and;
  331.              (b) Several alternatives in the pattern might
  332.              be valid at a given point, and we may need to
  333.              consider a shorter one in order to align with
  334.              word boundaries.  */
  335.           else if (whole_word)
  336.             while (len > 0)
  337.               {
  338.             /* If it's preceeded by a word constituent, then no go.  */
  339.             if (beg > 0
  340.                 && WCHAR((unsigned char) matching_line[beg - 1]))
  341.               break;
  342.             /* If it's followed by a word constituent, look for
  343.                a shorter match.  */
  344.             else if (beg + len < maxlen
  345.                 && WCHAR((unsigned char) matching_line[beg + len]))
  346.               /* This is sheer incest. */
  347.               len = re_match_2 (®ex, (unsigned char *) 0, 0,
  348.                         matching_line, maxlen,
  349.                         beg, ®s, beg + len - 1);
  350.             else
  351.               goto succeed;
  352.               }
  353.           else
  354.             goto succeed;
  355.         }
  356.         fail:
  357.           resume = next_line;
  358.           if (resume == search_limit)
  359.         break;
  360.           else
  361.         continue;
  362.         }
  363.  
  364.     succeed:
  365.       /* Print out the matching or nonmatching lines as necessary. */
  366.       if (! nonmatching_lines)
  367.         {
  368.           /* Not -v, so nothing hairy... */
  369.           ++match_count;
  370.  
  371.           /* Print leftover trailing context from last time around.  */
  372.           while (pending_lines && last_match_limit < matching_line)
  373.         {
  374.           last_match_limit += print_line(last_match_limit,
  375.                          initial_line_count++,
  376.                          0);
  377.           --pending_lines;
  378.         }
  379.  
  380.           /* Back up over leading context if necessary. */
  381.           for (i = leading_context;
  382.            i > 0 && matching_line > printed_limit;
  383.            --i)
  384.         {
  385.           while (matching_line > printed_limit
  386.              && (--matching_line)[-1] != '\n')
  387.             ;
  388.           --line_count;
  389.         }
  390.  
  391.           /* If context is enabled, we may have to print a separator. */
  392.           if ((leading_context || trailing_context) && !silent
  393.           && !first_match && (printed_limit_fake
  394.                       || matching_line > printed_limit))
  395.         printf("----------\n");
  396.           first_match = 0;
  397.  
  398.           /* Print the matching line and its leading context. */
  399.           while (matching_line < real_matching_line)
  400.         matching_line += print_line(matching_line, line_count++, 0);
  401.           matching_line += print_line(matching_line, line_count++, 1);
  402.  
  403.           /* If there's trailing context, leave some lines pending until
  404.          next time. */
  405.           pending_lines = trailing_context;
  406.         }
  407.       else if (matching_line == last_match_limit)
  408.         {
  409.           /* In the -v case, this is where we deal with leftover
  410.          trailing context from last time... */
  411.           if (pending_lines > 0)
  412.         {
  413.           --pending_lines;
  414.           print_line(matching_line, line_count, 0);
  415.         }
  416.           ++line_count;
  417.         }
  418.       else if (matching_line > last_match_limit)
  419.         {
  420.           char *start = last_match_limit;
  421.  
  422.           /* Back up over leading context if necessary. */
  423.           for (i = leading_context; start > printed_limit && i; --i)
  424.         {
  425.           while (start > printed_limit && (--start)[-1] != '\n')
  426.             ;
  427.           --initial_line_count;
  428.         }
  429.  
  430.           /* If context is enabled, we may have to print a separator. */
  431.           if ((leading_context || trailing_context) && !silent
  432.           && !first_match && (printed_limit_fake
  433.                       || start > printed_limit))
  434.         printf("----------\n");
  435.           first_match = 0;
  436.  
  437.           /* Print out the presumably matching leading context. */
  438.           while (start < last_match_limit)
  439.         start += print_line(start, initial_line_count++, 0);
  440.  
  441.           /* Print out the nonmatching lines prior to the matching line. */
  442.           while (start < matching_line)
  443.         {
  444.           /* This counts as a "matching line" in -v. */
  445.           ++match_count;
  446.           start += print_line(start, initial_line_count++, 1);
  447.         }
  448.  
  449.           /* Deal with trailing context.  In -v what this means is
  450.          we print the current (matching) line, marked as a non
  451.          matching line.  */
  452.           if (trailing_context)
  453.         {
  454.           print_line(matching_line, line_count, 0);
  455.           pending_lines = trailing_context - 1;
  456.         }
  457.  
  458.           /* Count the current line. */
  459.           ++line_count;
  460.         }
  461.       else
  462.         /* Let us pray this never happens... */
  463.         abort();
  464.  
  465.       /* Resume searching at the beginning of the next line. */
  466.       initial_line_count = line_count;
  467.       resume = next_line;
  468.       last_match_limit = next_line;
  469.  
  470.       if (resume == search_limit)
  471.         break;
  472.     }
  473.  
  474.       /* Restore the saved character. */
  475.       *search_limit = saved_char;
  476.  
  477.       if (! nonmatching_lines)
  478.     {
  479.       while (last_match_limit < search_limit && pending_lines)
  480.         {
  481.           last_match_limit += print_line(last_match_limit,
  482.                          initial_line_count++,
  483.                          0);
  484.           --pending_lines;
  485.         }
  486.     }
  487.       else if (search_limit > last_match_limit)
  488.     {
  489.       char *start = last_match_limit;
  490.  
  491.       /* Back up over leading context if necessary. */
  492.       for (i = leading_context; start > printed_limit && i; --i)
  493.         {
  494.           while (start > printed_limit && (--start)[-1] != '\n')
  495.         ;
  496.           --initial_line_count;
  497.         }
  498.  
  499.       /* If context is enabled, we may have to print a separator. */
  500.       if ((leading_context || trailing_context) && !silent
  501.           && !first_match && (printed_limit_fake
  502.                   || start > printed_limit))
  503.         printf("----------\n");
  504.       first_match = 0;
  505.  
  506.       /* Print out all the nonmatching lines up to the search limit. */
  507.       while (start < last_match_limit)
  508.         start += print_line(start, initial_line_count++, 0);
  509.       while (start < search_limit)
  510.         {
  511.           ++match_count;
  512.           start += print_line(start, initial_line_count++, 1);
  513.         }
  514.  
  515.       pending_lines = trailing_context;
  516.       resume_index = 0;
  517.       retain = bufbytes - (search_limit - buffer);
  518.       continue;
  519.     }
  520.       
  521.       /* Save the trailing end of the buffer for possible use as leading
  522.      context in the future. */
  523.       i = leading_context;
  524.       tmp = search_limit;
  525.       while (tmp > printed_limit && i--)
  526.     while (tmp > printed_limit && (--tmp)[-1] != '\n')
  527.       ;
  528.       resume_index = search_limit - tmp;
  529.       retain = bufbytes - (tmp - buffer);
  530.       if (tmp > printed_limit)
  531.     printed_limit_fake = 1;
  532.     }
  533.  
  534.   return match_count;
  535. }
  536.  
  537. void
  538. usage_and_die()
  539. {
  540.   fprintf(stderr, "\
  541. Usage: %s [-CVbchilnsvwx] [-num] [-A num] [-B num] [-f file]\n\
  542.        [-e] expr [file...]\n", prog);
  543.   exit(ERROR);
  544. }
  545.  
  546. static char version[] = "GNU e?grep, version 1.6";
  547.  
  548. int
  549. main(argc, argv)
  550.      int argc;
  551.      char **argv;
  552. {
  553.   int c;
  554.   int ignore_case = 0;        /* Compile the regexp to ignore case. */
  555.   char *the_regexp = 0;        /* The regular expression. */
  556.   int regexp_len;        /* Length of the regular expression. */
  557.   char *regexp_file = 0;    /* File containing parallel regexps. */
  558.   int count_lines = 0;        /* Display only a count of matching lines. */
  559.   int list_files = 0;        /* Display only the names of matching files. */
  560.   int line_count = 0;        /* Count of matching lines for a file. */
  561.   int matches_found = 0;    /* True if matches were found. */
  562.   char *regex_errmesg;        /* Error message from regex routines. */
  563.   char translate[_NOTCHAR];    /* Translate table for case conversion
  564.                    (needed by the backtracking matcher). */
  565.  
  566.   if (prog = index(argv[0], '/'))
  567.     ++prog;
  568.   else
  569.     prog = argv[0];
  570.  
  571.   opterr = 0;
  572.   while ((c = getopt(argc, argv, "0123456789A:B:CVbce:f:hilnsvwx")) != EOF)
  573.     switch (c)
  574.       {
  575.       case '?':
  576.     usage_and_die();
  577.     break;
  578.  
  579.       case '0':
  580.       case '1':
  581.       case '2':
  582.       case '3':
  583.       case '4':
  584.       case '5':
  585.       case '6':
  586.       case '7':
  587.       case '8':
  588.       case '9':
  589.     trailing_context = 10 * trailing_context + c - '0';
  590.     leading_context = 10 * leading_context + c - '0';
  591.     break;
  592.  
  593.       case 'A':
  594.     if (! sscanf(optarg, "%d", &trailing_context)
  595.         || trailing_context < 0)
  596.       usage_and_die();
  597.     break;
  598.  
  599.       case 'B':
  600.     if (! sscanf(optarg, "%d", &leading_context)
  601.         || leading_context < 0)
  602.       usage_and_die();
  603.     break;
  604.  
  605.       case 'C':
  606.     trailing_context = leading_context = 2;
  607.     break;
  608.  
  609.       case 'V':
  610.     fprintf(stderr, "%s\n", version);
  611.     break;
  612.  
  613.       case 'b':
  614.     byte_count = 1;
  615.     break;
  616.  
  617.       case 'c':
  618.     count_lines = 1;
  619.     silent = 1;
  620.     break;
  621.  
  622.       case 'e':
  623.     /* It doesn't make sense to mix -f and -e. */
  624.     if (regexp_file)
  625.       usage_and_die();
  626.     the_regexp = optarg;
  627.     break;
  628.  
  629.       case 'f':
  630.     /* It doesn't make sense to mix -f and -e. */
  631.     if (the_regexp)
  632.       usage_and_die();
  633.     regexp_file = optarg;
  634.     break;
  635.  
  636.       case 'h':
  637.     no_filenames = 1;
  638.     break;
  639.  
  640.       case 'i':
  641.     ignore_case = 1;
  642.     for (c = 0; c < _NOTCHAR; ++c)
  643.       if (isupper(c))
  644.         translate[c] = tolower(c);
  645.       else
  646.         translate[c] = c;
  647.     regex.translate = translate;
  648.     break;
  649.  
  650.       case 'l':
  651.     list_files = 1;
  652.     silent = 1;
  653.     break;
  654.  
  655.       case 'n':
  656.     line_numbers = 1;
  657.     break;
  658.  
  659.       case 's':
  660.     silent = 1;
  661.     break;
  662.  
  663.       case 'v':
  664.     nonmatching_lines = 1;
  665.     break;
  666.  
  667.       case 'w':
  668.     whole_word = 1;
  669.     break;
  670.  
  671.       case 'x':
  672.     whole_line = 1;
  673.     break;
  674.  
  675.       default:
  676.     /* This can't happen. */
  677.     fprintf(stderr, "%s: getopt(3) let one by!\n", prog);
  678.     usage_and_die();
  679.     break;
  680.       }
  681.  
  682.   /* Set the syntax depending on whether we are EGREP or not. */
  683. #ifdef EGREP
  684.   regsyntax(RE_SYNTAX_EGREP, ignore_case);
  685.   re_set_syntax(RE_SYNTAX_EGREP);
  686. #else
  687.   regsyntax(RE_SYNTAX_GREP, ignore_case);
  688.   re_set_syntax(RE_SYNTAX_GREP);
  689. #endif
  690.  
  691.   /* Compile the regexp according to all the options. */
  692.   if (regexp_file)
  693.     {
  694.       FILE *fp = fopen(regexp_file, "r");
  695.       int len = 256;
  696.       int i = 0;
  697.  
  698.       if (! fp)
  699.     {
  700.       fprintf(stderr, "%s: %s: %s\n", prog, regexp_file,
  701.           sys_errlist[errno]);
  702.       exit(ERROR);
  703.     }
  704.  
  705.       the_regexp = malloc(len);
  706.       while ((c = getc(fp)) != EOF)
  707.     {
  708.       the_regexp[i++] = c;
  709.       if (i == len)
  710.         the_regexp = realloc(the_regexp, len *= 2);
  711.     }
  712.       fclose(fp);
  713.       /* Nuke the concluding newline so we won't match the empty string. */
  714.       if (i > 0 && the_regexp[i - 1] == '\n')
  715.     --i;
  716.       regexp_len = i;
  717.     }
  718.   else if (! the_regexp)
  719.     {
  720.       if (optind >= argc)
  721.     usage_and_die();
  722.       the_regexp = argv[optind++];
  723.       regexp_len = strlen(the_regexp);
  724.     }
  725.   else
  726.     regexp_len = strlen(the_regexp);
  727.   
  728.   if (whole_word || whole_line)
  729.     {
  730.       /* In the whole-word case, we use the pattern:
  731.      (^|[^A-Za-z_])(userpattern)([^A-Za-z_]|$).
  732.      In the whole-line case, we use the pattern:
  733.      ^(userpattern)$.
  734.      BUG: Using [A-Za-z_] is locale-dependent!  */
  735.  
  736.       char *n = malloc(regexp_len + 50);
  737.       int i = 0;
  738.  
  739. #ifdef EGREP
  740.       if (whole_word)
  741.     strcpy(n, "(^|[^A-Za-z_])(");
  742.       else
  743.     strcpy(n, "^(");
  744. #else
  745.       /* Todo:  Make *sure* this is the right syntax.  Down with grep! */
  746.       if (whole_word)
  747.     strcpy(n, "\\(^\\|[^A-Za-z_]\\)\\(");
  748.       else
  749.     strcpy(n, "^\\(");
  750. #endif
  751.       i = strlen(n);
  752.       bcopy(the_regexp, n + i, regexp_len);
  753.       i += regexp_len;
  754. #ifdef EGREP
  755.       if (whole_word)
  756.     strcpy(n + i, ")([^A-Za-z_]|$)");
  757.       else
  758.     strcpy(n + i, ")$");
  759. #else
  760.       if (whole_word)
  761.     strcpy(n + i, "\\)\\([^A-Za-z_]\\|$\\)");
  762.       else
  763.     strcpy(n + i, "\\)$");
  764. #endif
  765.       i += strlen(n + i);
  766.       regcompile(n, i, ®, 1);
  767.     }
  768.   else
  769.     regcompile(the_regexp, regexp_len, ®, 1);
  770.  
  771.   
  772.   if (regex_errmesg = re_compile_pattern(the_regexp, regexp_len, ®ex))
  773.     regerror(regex_errmesg);
  774.   
  775.   /*
  776.     Find the longest metacharacter-free string which must occur in the
  777.     regexpr, before short-circuiting regexecute() with Boyer-Moore-Gosper.
  778.     (Conjecture:  The problem in general is NP-complete.)  If there is no
  779.     such string (like for many alternations), then default to full automaton
  780.     search.  regmust() code and heuristics [see dfa.c] courtesy
  781.     Arthur David Olson.
  782.     */
  783.   if (line_numbers == 0 && nonmatching_lines == 0)
  784.     {
  785.       if (reg.mustn == 0 || reg.mustn == MUST_MAX ||
  786.         index(reg.must, '\0') != reg.must + reg.mustn)
  787.     bmgexec = 0;
  788.       else
  789.     {
  790.       reg.must[reg.mustn] = '\0';
  791.       if (getenv("MUSTDEBUG") != NULL)
  792.         (void) printf("must have: \"%s\"\n", reg.must);
  793.       bmg_setup(reg.must, ignore_case);
  794.       bmgexec = 1;
  795.     }
  796.     }
  797.   
  798.   if (argc - optind < 2)
  799.     no_filenames = 1;
  800.  
  801.   initialize_buffer();
  802.  
  803.   if (argc > optind)
  804.     while (optind < argc)
  805.       {
  806.     bufprev = eof = 0;
  807.     filename = argv[optind++];
  808.     fd = open(filename, 0, 0);
  809.     if (fd < 0)
  810.       {
  811.         fprintf(stderr, "%s: %s: %s\n", prog, filename,
  812.             sys_errlist[errno]);
  813.         error = 1;
  814.         continue;
  815.       }
  816.     if (line_count = grep())
  817.       matches_found = 1;
  818.     close(fd);
  819.     if (count_lines)
  820.       if (!no_filenames)
  821.         printf("%s:%d\n", filename, line_count);
  822.       else
  823.         printf("%d\n", line_count);
  824.     else if (list_files && line_count)
  825.       printf("%s\n", filename);
  826.       }
  827.   else
  828.     {
  829.       if (line_count = grep())
  830.     matches_found = 1;
  831.       if (count_lines)
  832.     printf("%d\n", line_count);
  833.       else if (list_files && line_count)
  834.     printf("<stdin>\n");
  835.     }
  836.  
  837.   if (error)
  838.     exit(ERROR);
  839.   if (matches_found)
  840.     exit(MATCHES_FOUND);
  841.   exit(NO_MATCHES_FOUND);
  842.   return NO_MATCHES_FOUND;
  843. }
  844.  
  845. /* Needed by the regexp routines.  This could be fancier, especially when
  846.    dealing with parallel regexps in files. */
  847. void
  848. regerror(s)
  849.      const char *s;
  850. {
  851.   fprintf(stderr, "%s: %s\n", prog, s);
  852.   exit(ERROR);
  853. }
  854.  
  855. /*
  856.    bmg_setup() and bmg_search() adapted from:
  857.      Boyer/Moore/Gosper-assisted 'egrep' search, with delta0 table as in
  858.      original paper (CACM, October, 1977).  No delta1 or delta2.  According to
  859.      experiment (Horspool, Soft. Prac. Exp., 1982), delta2 is of minimal
  860.      practical value.  However, to improve for worst case input, integrating
  861.      the improved Galil strategies (Apostolico/Giancarlo, Siam. J. Comput.,
  862.      February 1986) deserves consideration.
  863.  
  864.      James A. Woods                Copyleft (C) 1986, 1988
  865.      NASA Ames Research Center
  866. */
  867.  
  868. char *
  869. execute(r, begin, end, newline, count, try_backref)
  870.   struct regexp *r;
  871.   char *begin;
  872.   char *end;
  873.   int newline;
  874.   int *count;
  875.   int *try_backref;
  876. {
  877.   register char *p, *s;
  878.   char *match;
  879.   char *start = begin;
  880.   char save;            /* regexecute() sentinel */
  881.   int len;
  882.   char *bmg_search();
  883.  
  884.   if (!bmgexec)            /* full automaton search */
  885.     return(regexecute(r, begin, end, newline, count, try_backref));
  886.   else
  887.     {
  888.       len = end - begin; 
  889.       while ((match = bmg_search((unsigned char *) start, len)) != NULL)
  890.     {
  891.       p = match;        /* narrow search range to submatch line */
  892.       while (p > begin && *p != '\n')
  893.         p--;
  894.       s = match;
  895.       while (s < end && *s != '\n')
  896.         s++;
  897.       s++;
  898.  
  899.       save = *s;
  900.       *s = '\0';
  901.       match = regexecute(r, p, s, newline, count, try_backref);
  902.       *s = save;
  903.  
  904.       if (match != NULL)
  905.         return((char *) match);
  906.       else
  907.         {
  908.           start = s;
  909.           len = end - start;
  910.         }
  911.     }
  912.       return(NULL);
  913.     }
  914. }
  915.  
  916. int        delta0[256];
  917. unsigned char   cmap[256];        /* (un)folded characters */
  918. unsigned char    pattern[5000];
  919. int        patlen;
  920.  
  921. char *
  922. bmg_search(buffer, buflen)
  923.   unsigned char *buffer;
  924.   int buflen;
  925. {
  926.   register unsigned char *k, *strend, *s, *buflim;
  927.   register int t;
  928.   int j;
  929.  
  930.   if (patlen > buflen)
  931.     return NULL;
  932.  
  933.   buflim = buffer + buflen;
  934.   if (buflen > patlen * 4)
  935.     strend = buflim - patlen * 4;
  936.   else
  937.     strend = buffer;
  938.  
  939.   s = buffer;
  940.   k = buffer + patlen - 1;
  941.  
  942.   for (;;)
  943.     {
  944.       /* The dreaded inner loop, revisited. */
  945.       while (k < strend && (t = delta0[*k]))
  946.     {
  947.       k += t;
  948.       k += delta0[*k];
  949.       k += delta0[*k];
  950.     }
  951.       while (k < buflim && delta0[*k])
  952.     ++k;
  953.       if (k == buflim)
  954.     break;
  955.     
  956.       j = patlen - 1;
  957.       s = k;
  958.       while (--j >= 0 && cmap[*--s] == pattern[j])
  959.     ;
  960.       /* 
  961.     delta-less shortcut for literati, but 
  962.     short shrift for genetic engineers.
  963.       */
  964.       if (j >= 0)
  965.     k++;
  966.       else         /* submatch */
  967.     return ((char *)k);
  968.     }
  969.   return(NULL);
  970. }
  971.  
  972. int
  973. bmg_setup(pat, folded)            /* compute "boyer-moore" delta table */
  974.   char *pat;
  975.   int folded;
  976. {                    /* ... HAKMEM lives ... */
  977.   int j;
  978.  
  979.   patlen = strlen(pat);
  980.  
  981.   if (folded)                 /* fold case while saving pattern */
  982.     for (j = 0; j < patlen; j++) 
  983.       pattern[j] = (isupper((int) pat[j]) ?
  984.     (char) tolower((int) pat[j]) : pat[j]);
  985.   else
  986.       bcopy(pat, pattern, patlen);
  987.  
  988.   for (j = 0; j < 256; j++)
  989.     {
  990.       delta0[j] = patlen;
  991.       cmap[j] = (char) j;        /* could be done at compile time */
  992.     }
  993.   for (j = 0; j < patlen - 1; j++)
  994.     delta0[pattern[j]] = patlen - j - 1;
  995.   delta0[pattern[patlen - 1]] = 0;
  996.  
  997.   if (folded)
  998.     {
  999.       for (j = 0; j < patlen - 1; j++)
  1000.     if (islower((int) pattern[j]))
  1001.       delta0[toupper((int) pattern[j])] = patlen - j - 1;
  1002.     if (islower((int) pattern[patlen - 1]))
  1003.       delta0[toupper((int) pattern[patlen - 1])] = 0;
  1004.       for (j = 'A'; j <= 'Z'; j++)
  1005.     cmap[j] = (char) tolower((int) j);
  1006.     }
  1007. }
  1008.